<?php
echo "==========================================\n";
echo "  完成数据初始化\n";
echo "==========================================\n\n";

$pdo = new PDO('mysql:host=localhost;dbname=oa5;charset=utf8mb4', 'root', '123456', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$start = time();

// 1. 更新案件数据（使用正确的cid字段）
echo "1. 更新案件数据...\n";
$sql = "UPDATE oa_customer
SET
    case_num = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE cid = oa_customer.id AND delete_time = 0
    ),
    case_processing = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE cid = oa_customer.id AND status IN (1,2,3) AND delete_time = 0
    ),
    case_finished = (
        SELECT COUNT(*) FROM oa_lawcase
        WHERE cid = oa_customer.id AND status IN (4,5) AND delete_time = 0
    )";
$pdo->exec($sql);
echo "   ✓ 案件数据更新完成\n\n";

$duration = time() - $start;
echo "✓ 数据初始化完成，耗时: " . $duration . " 秒\n\n";

// 显示最终统计信息
echo "最终数据统计:\n";
$stmt = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(is_member = 1) AS members,
        SUM(contract_num > 0) AS has_contracts,
        SUM(case_num > 0) AS has_cases,
        SUM(contract_amount) AS total_amount
    FROM oa_customer WHERE delete_time = 0
");
$stats = $stmt->fetch();
echo "  总客户数: " . number_format($stats['total']) . "\n";
echo "  会员客户: " . number_format($stats['members']) . "\n";
echo "  有合同客户: " . number_format($stats['has_contracts']) . "\n";
echo "  有案件客户: " . number_format($stats['has_cases']) . "\n";
echo "  合同总金额: ¥" . number_format($stats['total_amount'], 2) . "\n\n";

// 显示样本数据
echo "样本数据 (前5个客户):\n";
$stmt = $pdo->query("
    SELECT id, name, is_member, contract_num, contract_amount, case_num
    FROM oa_customer WHERE delete_time = 0
    ORDER BY contract_amount DESC
    LIMIT 5
");
while ($row = $stmt->fetch()) {
    echo sprintf(
        "  ID: %d, 名称: %s, 会员: %s, 合同: %d个(¥%s), 案件: %d个\n",
        $row['id'],
        $row['name'],
        $row['is_member'] ? '✓' : ' ',
        $row['contract_num'],
        number_format($row['contract_amount'], 0),
        $row['case_num']
    );
}

echo "\n==========================================\n";
echo "  初始化完成！\n";
echo "==========================================\n";
